import tkinter as tk
from ...shoudongfasong.ui_demo_toplevel import ZCAN_Demo_Toplevel
from ....utils.loggers import ic_debugger
from tkinter import messagebox
import time
from ....zlgcan.zlgcan import *
import json

from ....utils.types import TestData_Type, Uds_Request_Type, UnitTestConfig_Type, Can_TestDataStucture, UnitTestDataStructure
from ..ecu_units.common_unit import CommonUnit_UI

MAX_RCV_NUM = 10


class Uds_unitTab_Frame(tk.Frame):
    def __init__(self, master, masterUI, parentWin):
        super().__init__(master=master)
        self.masterUI = masterUI
        self.parentWin = parentWin

        self.uds_unitTabInit()

    def uds_unitTabInit(self):
        self.unitTabDataInit()
        self.unitTab_test_config_info_update()
        self.unitTabViewInit()

    def unitTabDataInit(self):
        self.unitTab_UNIT_POS_LIST = []
        self.unitTab_UNIT_FUN_DICT = {}
        self.unitTab_UNIT_BTN_DICT = {}

        # DOC: 单元测试配置信息
        self.unitTab_UNIT_TEST_CONFIG_DICT: dict[str, UnitTestConfig_Type] = {
        }
        MAX_ROW = 6
        MAX_COLUMN = 8
        for i in range(MAX_ROW):
            for j in range(MAX_COLUMN):
                position = f"{i}{j}"
                self.unitTab_UNIT_POS_LIST.append(position)

        def default_unit_pos_btn_click(i, j):
            return lambda: messagebox.showinfo("提示", f"unit R{i}C{j}未定义")
        for pos in self.unitTab_UNIT_POS_LIST:
            self.unitTab_UNIT_FUN_DICT[pos] = default_unit_pos_btn_click
            self.unitTab_UNIT_TEST_CONFIG_DICT[pos] = UnitTestConfig_Type(pos=pos, name=f'unit_{pos}', zh_name=f'单元测试_{pos}',
                                                                          srcAddr=int(pos, 16), dstAddr=int(pos, 16)+0x80, Learmask=0xaaaaaaaa
                                                                          )

    def unitTab_btn_function_Init(self, i, j):
        return lambda: CommonUnit_UI(masterUI=self.masterUI, unitConfig=self.unitTab_UNIT_TEST_CONFIG_DICT[f'{i}{j}'])

    def unitTab_test_config_info_update(self):
        # DOC: 读取配置文件，更新unit_test
        with open('config/unit_test.json', 'r', encoding='utf-8') as f:
            self.unitTab_UNIT_TEST_CONFIG_JSON_INFO = json.load(f)

        for pos in self.unitTab_UNIT_POS_LIST:
            if pos in self.unitTab_UNIT_TEST_CONFIG_JSON_INFO:
                curUnitConfig = self.unitTab_UNIT_TEST_CONFIG_JSON_INFO[pos]
                pass
                self.unitTab_UNIT_TEST_CONFIG_DICT[pos] = UnitTestConfig_Type(
                    **curUnitConfig)
                # DOC 如果配置文件中有定义，则使用配置文件中的配置
                self.unitTab_UNIT_FUN_DICT[pos] = self.unitTab_btn_function_Init
                # self.unitTab_UNIT_BTN_DICT[pos].config(state=tk.NORMAL)

        # DOC 手工更新unit_test
        # DOC 针对每个位置的按钮，定义unit_function_update_,格式的函数
        # 这里自动更新已经定义的函数，否则就用默认的函数
        self.unitTab_btn_function_update()

    def unitTab_btn_function_update(self):
        for pos in self.unitTab_UNIT_POS_LIST:
            update_function = getattr(
                self, f'unit_function_update_{pos}', None)
            if update_function:
                update_function()

    def unit_function_update_02(self):
        def unit02(i, j):
            def wrapper():
                messagebox.showinfo('提示', 'unit00-update......')
            return wrapper
        self.unitTab_UNIT_FUN_DICT['02'] = unit02

    def unitTabViewInit(self):
        for i, j in self.unitTab_UNIT_POS_LIST:
            self.unitTab_UNIT_BTN_DICT[f"{i}{j}"] = tk.Button(
                self, text=self.unitTab_UNIT_TEST_CONFIG_DICT[f'{i}{j}'].name, state=tk.DISABLED, padx=10, pady=5, command=self.unitTab_UNIT_FUN_DICT[f'{i}{j}'](i, j))
            self.unitTab_UNIT_BTN_DICT[f"{i}{j}"].grid(row=i, column=j)

        # 把配置文件中有定义的按钮设置为可用
        for pos in self.unitTab_UNIT_TEST_CONFIG_JSON_INFO:
            self.unitTab_UNIT_BTN_DICT[pos].configure(state=tk.NORMAL)

        # DOC 调整行列最小间距
        col_count, row_count = self.grid_size()
        for col in range(col_count):
            self.grid_columnconfigure(col, minsize=110)
        for row in range(row_count):
            self.grid_rowconfigure(row, minsize=60)
